#!/usr/local/bin/python3

__author__ = '曹植'

import os
from yyd_joint_login import joint_login_function
from sql.yyd_sql import BaseSql
from threading import Thread
from flask import Flask, jsonify, request
from pyapollo.apollo_client import ApolloClient
from spiders.channel_id_26 import ChannelId26
from spiders.channel_id_3 import ChannelId3
from yyd_zk_api import check_account_function
from log import logger

app = Flask(__name__)


@app.route('/yyd/channel/zk', methods=['POST'])
def index():
    """优逸贷爬虫撞库接口"""
    count = 0
    result = jsonify({'code': 1, 'status': '失败', 'count': count})
    spiders = {3: ChannelId3, 26: ChannelId26}
    yyd_channel_sql = BaseSql(eval(s))
    try:
        mobile = int(request.get_json()['mobile'])
    except:
        return jsonify({'code': 2, 'status': '传入json格式数据的手机号码'})
    try:
        usable_channels = dict(yyd_channel_sql.query_usable_channel())
        uid = yyd_channel_sql.query_uid_by_mobile(mobile)
        id_card = yyd_channel_sql.query_id_card_by_mobile(mobile)
        # 判定该电话号码是否在用户注册表里面
        if uid is None:
            return jsonify({'code': 2, 'status': '无该用户', 'count': count})
        for channel_id, spider in spiders.items():
            # 判定爬虫支持的渠道是否已经下架
            channel_status = client.get_value('zk_switch_' + str(channel_id), 1)
            if int(channel_status) == 2:
                continue
            if channel_id not in usable_channels:
                continue
            # 判定该用户是否在该渠道已经撞库
            hit_info = yyd_channel_sql.query_storehouse(uid, channel_id)
            if hit_info:
                continue
            result = spider(id_card).check_account(str(mobile))
            if result['isRegister'] is True:
                count += 1
                yyd_channel_sql.update_storehouse(uid, channel_id, usable_channels[channel_id])
        result = jsonify({'code': 0, 'status': '成功', 'count': count})
    except Exception as e:
        logger.exception('非爬虫错误,{}'.format(e))
    finally:
        yyd_channel_sql.close()
    return result


@app.route('/yyd/channel/api/zk', methods=['POST'])
def zk_view():
    try:
        uid = int(request.get_json()['uid'])
    except:
        return jsonify({'code': 2, 'status': '传入json格式数据'})
    try:
        yyd_channel_sql = BaseSql(eval(s))
        yyd_thread = Thread(target=check_account_function, args=(yyd_channel_sql, uid))
        yyd_thread.start()
        return jsonify({'code': 0, 'status': '成功'})
    except Exception as e:
        logger.exception('优逸贷渠道api撞库出错,{}'.format(e))
        return jsonify({'code': 1, 'status': '失败'})


@app.route('/yyd/joint/login', methods=['POST'])
def joint_login_view():
    try:
        uid = int(request.get_json()['uid'])
        channel_id = request.get_json()['channel_id']
    except:
        return jsonify({'code': 2, 'status': '传入json格式数据'})
    try:
        channel_addr = client.get_value('channel_' + channel_id, None)
        if not channel_addr:
            return jsonify({'code': 4, 'status': 'apollo无该配置'})
        yyd_channel_sql = BaseSql(eval(s))
        info = joint_login_function(channel_id, yyd_channel_sql, uid, channel_addr)
        return jsonify(info)
    except Exception as e:
        logger.exception('优逸贷联合登录出错,{}'.format(e))
        return jsonify({'code': 1, 'status': '失败'})


if __name__ == '__main__':
    dic = {'DEV': 'http://192.168.1.202:8080', 'FAT': 'http://192.168.1.204:8080', 'PRO': 'http://172.18.55.34:8080'}
    path = os.path.split(os.path.abspath(__file__))[0]
    with open(path + '/server.properties', 'r') as f:
        env = f.read().split('=')[1].strip().upper()
    client = ApolloClient(app_id=10011, cluster='default', config_server_url=dic.get(env))
    client.start()
    s = client.get_value('mysql_config', None)
    print('----mysql配置生效中-------')
    app.run(debug=False, host='0.0.0.0')
